import carApi from '@/api/car';
export default {
    namespaced:true,
    state:{
        carList:[]   //购物车
    },
    mutations:{
        SET_CARLIST(state,payload){
            state.carList = payload.map(item => {
                let target = state.carList.find(v => v.shopid === item.shopid);
                item.flag = false;
                if(target){
                    item.flag = target.flag ? target.flag : false;
                }
                
                return item
            });
        },
        SET_CHECKED(state,shop_id){
            state.carList.forEach(item => {
                if(item.shopid === shop_id){
                    item.flag = !item.flag
                }
            })
        }
    },
    actions:{
        getCarList({commit,rootState}){
            console.log(rootState)
            console.log(rootState.user.userinfo.uid)
            let uid = rootState.user.userinfo.uid;

            //取到user_id
            carApi.getCarList(uid).then(res => {
                if(res.data.code === 1){
                    commit('SET_CARLIST',res.data.data)
                }
            })
        },
        addCarAction({rootState,dispatch},shop_id){
            let uid = rootState.user.userinfo.uid;
            carApi.addCar(uid,shop_id).then(res => {
                if(res.data.code === 1){
                    console.log("添加成功");
                    dispatch("getCarList")
                }
            })
        },
        removeCarAction({rootState,dispatch},shop_id){
            let uid = rootState.user.userinfo.uid;
            carApi.removeCar(uid,shop_id).then(res => {
                if(res.data.code === 1){
                    dispatch("getCarList")
                }
            })
        },
        delCarAction({rootState,dispatch},shop_id){
            let uid = rootState.user.userinfo.uid;
            carApi.delCar(uid,shop_id).then(res => {
                if(res.data.code === 1){
                    dispatch("getCarList")
                }
            })
        }
    },
    getters:{
        sumPrice(state){
            return state.carList.reduce((prev,cur) => {
                console.log(prev,cur);
                if(cur.flag){
                    prev = prev + cur.shopdata.price*cur.count
                }
                return prev
            },0)
        }
    }
}